package exercise.jslide.jslide.model.shapes;

import javafx.scene.canvas.GraphicsContext;
import javafx.geometry.Point2D;

public class Line extends Shape {

    @Override
    protected void drawShape(GraphicsContext gc) {
        gc.strokeLine(x, y, x + width, y + height);
    }

    @Override
    public boolean contains(Point2D point) {
        double tolerance = 5.0; // 点击容差

        double lineLength = Math.sqrt(width * width + height * height);
        // 计算点到线段的距离 注意可能为负数
        double distance = Math.abs((point.getX() - x) * height - (point.getY() - y) * width) / lineLength;

        //如果超出矩形范围，返回false
        if (width < 0&&height<0) {
            if (point.getX() < x + width || point.getX() > x|| point.getY() < y + height || point.getY() > y) {
                return false;
            }else {
                return distance <= tolerance;
            }
        }else if (width < 0&&height>0) {
            if (point.getX() < x + width || point.getX() > x|| point.getY() < y || point.getY() > y + height) {
                return false;
            }else {
                return distance <= tolerance;
            }

        }else if (height < 0&&width>0) {
            if (point.getX() < x || point.getX() > x + width|| point.getY() < y + height || point.getY() > y) {
                return false;
            }else {
                return distance <= tolerance;
            }
        }else {
            if (point.getX() < x || point.getX() > x + width|| point.getY() < y || point.getY() > y + height) {
                return false;
            }else {
                return distance <= tolerance;
            }
        }
    }

    @Override
    public Shape clone() {
        Line clone = new Line();
        clone.x = this.x;
        clone.y = this.y;
        clone.width = this.width;
        clone.height = this.height;
        clone.strokeColor = this.strokeColor;
        clone.strokeWidth = this.strokeWidth;
        return clone;
    }
}